package com.ying.tests.AAAmode.strategy1.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ying.tests.AAAmode.strategy1.service.RobotService;
import com.ying.tests.AAAmode.strategy1.entity.BusinessLineEnum;
import com.ying.tests.AAAmode.strategy1.service.BusinessLineService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.EnumMap;

@Service
public class OneRobotServiceImpl implements RobotService, ApplicationListener<ContextRefreshedEvent> {

    private static final String BUSINESS_LINE = "businessId";
    private EnumMap<BusinessLineEnum, BusinessLineService> map = new EnumMap<>(BusinessLineEnum.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        String[] beanNamesForType = applicationContext.getBeanNamesForType(BusinessLineService.class);
        for (String beanName : beanNamesForType) {
            BusinessLineService bean = applicationContext.getBean(beanName, BusinessLineService.class);
            map.put(bean.businessLineEnum(), bean);
        }
    }

    @Override
    public void turnRobot(String message) {
        JSONObject messageJson = JSONObject.parseObject(message);
        String business = messageJson.getString(BUSINESS_LINE);
        BusinessLineService businessLineService = map.get(BusinessLineEnum.valueOf(business, BusinessLineEnum.BUSINESS_DEFAULT));
        businessLineService.process(messageJson);
    }

}
